package com.parkLot.spring.controller;

import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mingke.Domain.CustomerEntity;
import com.mingke.TransformObject.ValidationCodeTO;
import com.mingke.Utils.PageUtils;
import com.mingke.Utils.R;
import com.parkLot.spring.service.CustomerService;
import com.parkLot.spring.third.MessageUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;

import java.util.concurrent.TimeUnit;


/**
 * 
 *
 * @author mingke
 * @email 1510181330@qq.com
 * @date 2021-01-22 13:30:40
 */
@Slf4j
@RestController
@RequestMapping("/customer")
public class CustomerController {

    @Autowired
    private CustomerService customerService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private MessageUtils messageUtils;

    /**
     * 列表
     */
    @GetMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = customerService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @GetMapping("/info/{customerId}")
    public R info(@PathVariable("customerId") Integer customerId){
		CustomerEntity customer = customerService.getById(customerId);

        return R.ok().put("customer", customer);
    }

    /**
     * 保存
     */
    @PostMapping("/save")
    public R save(@RequestBody CustomerEntity customer){
        customer.setAddTime(new Date());
        customer.setUpdateTime(new Date());
        customer.setDeleted(0);
		customerService.save(customer);

        return R.ok();
    }

    /**
     * 修改
     */
    @PostMapping("/update")
    public R update(@RequestBody CustomerEntity customer){
        customer.setUpdateTime(new Date());
		customerService.updateById(customer);

        return R.ok();
    }

    /**
     * 删除
     */
    @PostMapping("/delete")
    public R delete(@RequestBody Integer[] customerIds){
		customerService.removeByIds(Arrays.asList(customerIds));

        return R.ok();
    }

    @PostMapping("/login")
    public R login(){
        System.out.println("有人");
        return R.ok();
    }

    @GetMapping("/getMessage")
    public R getMessage(@RequestParam("phone") String phone) throws IOException {
        String value = stringRedisTemplate.opsForValue().get(phone);
        //如果缓存中存在，就要检查是否过期
        if(!StringUtils.isEmpty(value)){
            //redis有，则进行超时检测
            Long l = Long.parseLong(value.split("_")[1]);

            if(System.currentTimeMillis() - l < 60000){
                return R.error("60s内仅能发送一次验证码");
            }
        }
        String code = UUID.randomUUID().toString().substring(0, 5)+"_"+System.currentTimeMillis();
        //验证码保存到redis，有效期为10分钟
        stringRedisTemplate.opsForValue().set(phone, code, 10, TimeUnit.MINUTES);
        return messageUtils.sendMessageByPost(phone, code.split("_")[0]);
    }

    @PostMapping("validationCode")
    public R validationCode(@RequestBody ValidationCodeTO to){
        String phone = to.getPhone();
        String code = to.getCode();
        if(code.equals("654321")){
            //测试用，避免用完短信包
            return R.ok("登陆成功").put("userkey", 1);
        }
        String redisCode = stringRedisTemplate.opsForValue().get(phone);
        if(StringUtils.isEmpty(redisCode)){
            return R.error("请使用手机号获取验证码");
        }

        String trueRedisCode = redisCode.split("_")[0];
        //redis有，则进行超时检测
        Long l = Long.parseLong(redisCode.split("_")[1]);

        if(System.currentTimeMillis() - l > 60000){
            log.info("验证码已经超时");
            return R.error("验证码已经超时");
        }
        if(code.equals(trueRedisCode)){
            log.info("登陆成功");
            QueryWrapper<CustomerEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("customer_phone", phone);
            CustomerEntity customer = customerService.list(queryWrapper).get(0);
            return R.ok("登陆成功").put("userkey", customer.getCustomerId());
        }else{
            log.info("验证码错误");
            return R.error("验证码错误");
        }
    }

}
